package com.sailing.xjpb.orm.query;

import lombok.Getter;
import org.springframework.core.Ordered;

import java.util.HashMap;
import java.util.Map;

/**
 * 动态查询条件的单元 also see {@linkplain QueryCondition}
 * <p>动态查询条件的单元包含以下信息:1.{@linkplain QueryCondition}的子类中一个查询字段对应的查询条件的信息,其中字段名称是key;2.sql查询条件;3.注入参数;4.排序值(数据量大的时候,
 * 将部分查询条件放置到最后,有利于查询速度)
 * key用于唯一标识查询单元;sql查询条件格式遵循sql中where部分表中,如: name like ?;注入参数防止sql注入依赖;排序值决定生成where条件部分的先后顺序
 *
 * @author YaoWei
 */
public class ConditionUnit implements Comparable<ConditionUnit>, Ordered {
    /**
     * 字段对应的生成的查询条件
     */
    @Getter
    private final StringBuilder conditions;
    /**
     * 注入参数
     */
    @Getter
    private Map<String, Object> params = new HashMap<>();
    /**
     * 排序值
     */
    private Integer order = Ordered.LOWEST_PRECEDENCE;


    public ConditionUnit(String conditions) {
        this.conditions = new StringBuilder(conditions);
    }

    public ConditionUnit(StringBuilder conditions) {
        this.conditions = conditions;
    }

    public static ConditionUnit of(StringBuilder conditions) {
        return new ConditionUnit(conditions);
    }

    public static ConditionUnit of(String conditions) {
        return new ConditionUnit(conditions);
    }

    @Override
    public int compareTo(ConditionUnit o) {
        return Integer.compare(this.getOrder(), o.getOrder());
    }

    @Override
    public int getOrder() {
        return order;
    }

    public ConditionUnit setOrder(Integer order) {
        this.order = order;
        return this;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

    /**
     * 添加注入参数
     */
    public ConditionUnit addParam(String paramKey, Object param) {
        params.put(paramKey, param);
        return this;
    }

    /**
     * 添加注入参数
     */
    public ConditionUnit addAllParam(Map<String, Object> params) {
        this.params.putAll(params);
        return this;
    }
}